from django.shortcuts import render, redirect

# Create your views here.
from .models import RegisterUser
# 首页
def index(request):
    login_msg = '恭喜!,登录成功'
    return  render(request, 'index.html',{'login_msg':login_msg})

# 登录
def login(request):
    if request.method == "GET":
        return render(request,'login.html')
    if request.method == "POST":

        userEmail = request.POST.get('username')
        userPassword = request.POST.get('password')

        try:
            user = RegisterUser.objects.get(reg_mail=userEmail)
            if userPassword == user.reg_pwd:
                return redirect('/index/')
            else:
                error_msg = '密码错误'
                return render(request,'login.html',{'error_msg':error_msg})
        except:
            error_msg = '用户名不存在'
            return render(request,'login.html',{'error_msg':error_msg})


def register(request):
    if request.method =='POST':
        userEmail = request.POST.get('userEmail')
        userPassword = request.POST.get('userPassword')
        userRePassword = request.POST.get('userRePassword')
        try:
            user = RegisterUser.objects.get(reg_mail=userEmail)
            if user:
                msg='用户名已存在'
                return render(request,'register.html',{'msg':msg})
        except:
            if userPassword != userRePassword:
                error_msg = '密码不一致'
                return render(request,'register.html',{'error_msg':error_msg})
            else:
                register = RegisterUser()
                register.reg_mail = userEmail
                register.reg_pwd = userPassword
                register.save()
                return redirect('/login/')
    else:
        return render(request,'register.html')